package mamikeji.liaowa.ui.activity.forum;

import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyForumBean;
import mamikeji.liaowa.bean.Web_Focus;
import mamikeji.liaowa.bean.Web_Praise;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.PreviewCircleImgActivity;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.widget.webview_js.DWebView;


public class ForumMSGActivity_copy extends BaseActivity {
    private static final String TAG = "ForumMSGActivity";
    @BindView(R.id.webView_forum_msg)
    DWebView webViewForumMsg;
    @BindView(R.id.progressBar_forum_msg)
    ProgressBar progressBarForumMsg;

    private MyForumBean.DataEntity dataEntity;

    boolean bool_forum_refresh = false;
    private Web_forum_changeBean web_forum_changeBean;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_msg);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webViewForumMsg.canGoBack()){
                    webViewForumMsg.goBack();
                }else {
                    if (bool_forum_refresh) {
                        Intent intent = new Intent();
                        intent.putExtra("web_forum_changeBean", web_forum_changeBean);
                        setResult(RESULT_OK, intent);
                    }
                    finish();
                }
            }
        });

        web_forum_changeBean = new Web_forum_changeBean(0, 0, 0, new ArrayList<Web_Focus>() , 0);
        dataEntity = (MyForumBean.DataEntity) getIntent().getSerializableExtra("MyForumBean");

        if (dataEntity.getCertification() == null) {
            setTitleName(dataEntity.getNickname());
        } else {
            setTitleName(dataEntity.getCertification().equals("") ?
                    dataEntity.getNickname() :
                    dataEntity.getNickname() + "(" + dataEntity.getCertification() + ")");
        }

        setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initCollectionDate();
            }
        });

        init();
    }

    private void init() {
        WebSettings webSettings = webViewForumMsg.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        webViewForumMsg.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        webViewForumMsg.setJavascriptInterface(new JsApi());

        webViewForumMsg.loadUrl(HttpApi.ROOT_PATH + HttpApi.FORUM_DATE +
                "?usercode=" + ForPreference.getString(ForContents.USER_CODE) +
                "&topic_id=" + dataEntity.getTopic_id());

        webViewForumMsg.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBarForumMsg.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    progressBarForumMsg.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBarForumMsg.setProgress(newProgress);//设置进度值
                }
            }

        });
    }

    /**
     * 收藏文章
     */
    private void initCollectionDate() {
        MobclickAgent.onEvent(this,"HotTopicCollection");//热门话题-收藏
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("topic_id", dataEntity.getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicCollection, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                ForLog.e(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bool_forum_refresh = true;
                        int num = ForPreference.getInt(ForContents.USER_COLLECTION);
                        if (dataEntity.getIs_collection() == 1) {
                            dataEntity.setIs_collection(0);
                            ForPreference.putInt(ForContents.USER_COLLECTION, --num);
                            ForToast.showToast(R.string.collection_delete);
                            web_forum_changeBean.setIsCollection(0);
                        } else {
                            dataEntity.setIs_collection(1);
                            ForPreference.putInt(ForContents.USER_COLLECTION, ++num);
                            ForToast.showToast(R.string.collection_success);
                            web_forum_changeBean.setIsCollection(1);
                        }

                        setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                                R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                initCollectionDate();
                            }
                        });
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        webViewForumMsg.onPause();
        MobclickAgent.onPageEnd("热门话题");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webViewForumMsg.onResume();
        MobclickAgent.onPageStart("热门话题");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webViewForumMsg.canGoBack()) {
            setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                    R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initCollectionDate();
                }
            });
            webViewForumMsg.goBack();// 返回前一个页面
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (bool_forum_refresh) {
                Intent intent = new Intent();
                intent.putExtra("web_forum_changeBean", web_forum_changeBean);
                setResult(RESULT_OK, intent);
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    class JsApi {
        //点击关注
        @JavascriptInterface
        public void clickFocus(JSONObject jsonObject) throws JSONException {
            String response = jsonObject.getString("msg");
            Web_Focus webFocus = new Gson().fromJson(response, Web_Focus.class);
            web_forum_changeBean.getWebFocusList().add(webFocus);
            ForLog.i("web_forum_changeBean", "" + web_forum_changeBean.getWebFocusList().size());
            bool_forum_refresh = true;
        }

        //点击回复或点赞
        @JavascriptInterface
        public void clickReplyOrThumb(JSONObject jsonObject) throws JSONException {
            String response = jsonObject.getString("msg");
            Web_Praise web_praise = new Gson().fromJson(response, Web_Praise.class);
            web_forum_changeBean.setZanStatic(web_praise.getBoolThumb());
            web_forum_changeBean.setZanNum(Integer.parseInt(web_praise.getThumbNum()));
            web_forum_changeBean.setCommentNum(Integer.parseInt(web_praise.getCommentsNum()));
            bool_forum_refresh = true;
        }

        //显示图片
        @JavascriptInterface
        public void displayImages(JSONObject jsonObject) throws JSONException {
            String response = jsonObject.getString("msg");
            Web_image_yrl web_image_yrl = new Gson().fromJson(response, Web_image_yrl.class);
            String[] split2 = dataEntity.getTopic_image().split(",");
            ArrayList<String> stringList = new ArrayList<String>();
            int index = 0;
            for (int i = 0; i < split2.length; i++) {
                if (split2[i].equals(web_image_yrl.getImageurl())) {
                    index = i;
                }
                stringList.add(split2[i]);
            }

            Intent intent = new Intent(ForumMSGActivity_copy.this, PreviewCircleImgActivity.class);
            intent.putStringArrayListExtra("urlList", stringList);
            intent.putExtra("position", index);
            ForumMSGActivity_copy.this.startActivity(intent);
        }

        //右上角收藏按钮显示状态
        @JavascriptInterface
        public void hideFavorites(JSONObject jsonObject) throws JSONException {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    TextView textView = setTitleRightBtn(R.string.forum_msg_right_0, null);
                    if (textView != null) {
                        textView.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    class Web_image_yrl {
        private String imageurl;
        private String imglist;

        public void setImageurl(String imageurl) {
            this.imageurl = imageurl;
        }

        public void setImglist(String imglist) {
            this.imglist = imglist;
        }

        public String getImageurl() {
            return imageurl;
        }

        public String getImglist() {
            return imglist;
        }
    }

    class Web_right {
        private int BoolhideFavorites;

        public void setBoolhideFavorites(int BoolhideFavorites) {
            this.BoolhideFavorites = BoolhideFavorites;
        }

        public int getBoolhideFavorites() {
            return BoolhideFavorites;
        }
    }

}
